<template>
  <section class='f-index' :style="{height: currentHeight}">
    <div>
      <header class="f-header">
        <section class="f-logo">
          <img style="width:100%;" src="@/assets/icons/mfb_logo.png" alt="">
        </section>
        <van-search v-model="searchForm.searchValue" shape="round" background="#0F9BFD" placeholder="请输入商品ID或商品名称" style="flex:1"
          @search="handleSearch(0)" />
        <section class="f-msg" @click="toMsg()">
          <van-badge :dot="dot">
            <img src="@/assets/icons/home_icon_message@2x.png" alt="" @click="toMsg">
          </van-badge>
        </section>
      </header>

      <van-swipe class="f-banner" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="(item,index) in bannerList" :key="index">
          <img style="width:100%;height:100%" :src="item.headImg" alt="" @click="toLinkUrl(item)">
        </van-swipe-item>
      </van-swipe>

      <ul class="f-tab">
        <li v-for="(item,index) in tableNav" :key="index" :class="{'f-activeTab': activeTab == index}"
          @click="handleSearch(index)">
          {{item}}
        </li>
      </ul>
    </div>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" style="overflow-y: auto;flex:1;">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <section class="f-cell-ground" v-for="(item,index) in tableData" :key="index">
          <section class="f-cell">
            <img class="f-goods-img" :src="item.headImg" alt="" @click="pageJump('/goods/detail',item)">
            <div style="padding: 9px 0 12px 103px" @click="pageJump('/goods/detail',item)">
              <p style="font-size: 16px;color: #333333;font-weight: 500;">{{item.goodsName}}</p>
              <section class="f-flex-between f-flex-end" style="margin-top:6px">
                <div style="font-size: 11px;font-weight: 300;color: #666666;">
                  <div class="g-flex-ct">
                    <p class="f-right" style="width:45px">面值：</p>{{ toThousands(item.preMoney) || '--'}}元
                  </div>
                  <div class="g-flex-ct">
                    <p class="f-right" style="width:45px">商品ID：</p>{{item.goodsId}}
                  </div>
                  <div class="g-flex-ct">
                    <p class="f-right" style="width:45px">归属地：</p>{{item.belongingPlace}}
                  </div>
                </div>
                <section class="f-pr-10">
                  <section class="g-flex-ct">
                    <p class="f-type" v-if="item.gaveTypeDay == 1">秒返</p>
                    <p class="f-type" v-if="item.gaveTypeMonth == 1">次月返</p>
                  </section>
                  <div class="f-flex-right">
                    <img style="width:12px;height:12px" src="@/assets/icons/home_icon_commission@2x.png" alt="">
                    <p style="font-size: 14px;color: #FF635D;margin-left:6px">{{ toThousands(item.income) || '--'}}元</p>
                  </div>
                </section>
              </section>
            </div>
            <div class="f-tips">
              <section class="ellipsis" style="width:300px;" @click="openIncome(item.incomeConfList)">
                <span v-for="(myItem,myIndex) in item.incomeConfList" :key="myIndex">
                  佣金规则{{item.incomeConfList.length>1?myIndex+1:''}}：{{myItem.runState == 1? '激活':'首充'}}-佣金{{myItem.income}}元,冻结期{{myItem.freezenDay}}{{myItem.gaveType == 1? '天': '月'}}
                </span>
              </section>
              <van-icon style="padding-top:2px" name="arrow" />
            </div>
            <div class="f-btn">
              <p style="color:#488BFE" @click="handleCopy(item)">复制链接</p>
              <p style="color:#488BFE" @click="createPoster(item)">生成海报</p>
              <p @click="pageJump('/goods/info',item)">查看资料</p>
            </div>
          </section>
        </section>
      </van-list>
    </van-pull-refresh>

    <van-overlay :show="off.overlay">
      <section v-if="off.overlay" id="posterHtml" class="f-overlay">
        <section class="f-overlay-card">
          <img style="width: 208px;height: 111px;border-radius: 10px;" :src="posterData.headImg" alt="">
          <p style="font-size: 16px;font-weight: 500;color: #333333;margin:5px 0 7px 0">{{posterData.goodsName}}</p>
          <p class="f-right" style="font-size: 10px;font-weight: 300;color: #FF635D;">面值: {{toThousands(posterData.preMoney)}}元
          </p>
          <div class="f-content">
            <p>运营商：{{posterData.operator}}</p>
            <p>归属地：{{posterData.belongingPlace}}</p>
          </div>
        </section>
        <section class="f-shop-info">
          <div class="g-flex-ct">
            <img style="width:34px;height:34px" src="@/assets/icons/icon_shop_head@2x.png" alt="">
            <p class="f-ml-10" style="font-size: 14px;font-weight: 500;">{{shopForm.shopName }}</p>
          </div>
          <div class="f-qr-code">
            <qrcode-vue style="width:81px;height:81px" :value="shopQrCode" :size="200" level="H" />

            <p class="f-mt-15" style="font-size: 12px;font-weight: 300;">扫码查看详情</p>
          </div>
        </section>
      </section>
    </van-overlay>

    <van-overlay :show="off.income">
      <div class="f-wrapper">
        <p style="font-weight: 500;font-size: 19px;color: #000000;">佣金规则</p>

        <section class="f-left f-mt-20">
          <div class="f-mt-05 f-ml-30 g-flex-ct" v-for="(item,index) in incomeConfList" :key="index">
            <p style="width:20px">{{index+1}}：</p>
            <p>{{item.runState == 1? '激活':'首充'}}-佣金{{item.income}}元,冻结期{{item.freezenDay}}{{item.gaveType == 1? '天': '月'}}</p>
          </div>
        </section>

        <div style="padding:21px 40px 0 40px">
          <van-button round block type="primary" color="#488BFE" @click="off.income =false">确定</van-button>
        </div>
      </div>
    </van-overlay>

    <van-share-sheet v-model:show="off.share" title="分享到" :options="shareList" @select="handleShare" :overlay="false"
      :round="false" @cancel="off.overlay = false" />

    <van-floating-bubble axis="xy" icon="chat" magnetic="x" @click="toShopShare()">
      <template #default>
        <div>
          <p>号卡</p>
          <p>店铺</p>
        </div>
      </template>
    </van-floating-bubble>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch, nextTick, onBeforeUnmount, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import api from './api'
import { getStore, successDeal, toThousands } from '@/utils/utils';
import html2canvas from 'html2canvas'
import JsBridge from '@/utils/JsBridge.js'
import { showLoadingToast, closeToast, showToast } from 'vant';
import QrcodeVue from 'qrcode.vue'

export default {
  name: 'goodsList',

  components: { QrcodeVue },

  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const state = reactive({
      off: {
        overlay: false,
        share: false,
        income: false,
      },

      userInfo: {},

      searchForm: {
        "gaveType": 0,
        "orderBy": "id desc",
        "searchValue": "",
        "page": 1,
        "size": 10
      },

      activeTab: 0,
      tableNav: ['全部商品', '秒返商品', '次月返商品'],

      loading: false,
      finished: false,
      refreshing: false,
      tableData: [],
      total: 0,

      currentHeight: '520px',

      posterData: {},
      posterImgURL: null,
      shareList: [
        { name: '微信', icon: 'wechat' },
        // { name: '朋友圈', icon: 'wechat-moments' },
        // { name: 'QQ', icon: 'qq' },
        { name: '保存图片', icon: 'poster' },
      ],

      incomeConfList: [],
      shopForm: {},

      shopQrCode: '',

      dot: false,
      timer: null,

      bannerList: [],

      isApp: computed(() => {
        return store.state.isApp
      })
    })

    onMounted(() => {
      store.commit("setNavBar", { show: false })

      state.currentHeight = window.innerHeight - 55 + 'px'

      state.userInfo = getStore('USER_INFO_MF')

      if (!state.isApp) {
        state.shareList = [
          // { name: '微信', icon: 'wechat' },
          // { name: '朋友圈', icon: 'wechat-moments' },
          // { name: 'QQ', icon: 'qq' },
          { name: '保存图片', icon: 'poster' },
        ]
      }

      getBannerList()
      getShopInfo()

      getMsg()
      state.timer = setInterval(() => {
        getMsg()
      }, 1000 * 60)
    })

    const getBannerList = () => {
      let json = {
        "orderBy": "",
        "page": 1,
        "size": 10,
        "type": 1
      }
      api.bannerList(json).then(res => {
        state.bannerList = res.data.list
      })
    }

    const getShopInfo = () => {
      api.shopInfo().then(res => {
        state.shopForm = res.data
      })
    }

    const getMsg = () => {
      api.newMessageCount().then(res => {
        if (res.data.count) {
          state.dot = true
        } else {
          state.dot = false
        }
      })
    }

    const onLoad = () => {
      let json = JSON.parse(JSON.stringify(state.searchForm))

      if (state.refreshing) {
        state.tableData = [];
        state.refreshing = false;
      }

      api.goodsList(json).then(res => {
        state.refreshing = false

        if (res.data.list.length) state.searchForm.page += 1
        state.tableData.push(...res.data.list)

        // 防止触发两次
        if (state.tableData.length >= res.data.total) {
          state.finished = true;
        } else {
          state.finished = false;
        }

        //   // 加载状态结束
        state.loading = false;

        // 数据全部加载完成
        if (state.tableData.length < 10) {
          state.finished = true;
        }
      }).catch(err => {
        state.loading = false;
        state.finished = true;
        state.refreshing = false
      })
    };

    const onRefresh = () => {
      state.searchForm.page = 1

      // 清空列表数据
      state.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      state.loading = true;
      onLoad();
    };

    const handleSearch = (activeTab) => {
      state.activeTab = activeTab
      state.searchForm.gaveType = activeTab

      state.refreshing = true
      onRefresh()
    }

    // 生成海报
    const createPoster = async (data) => {
      showLoadingToast({
        message: '生成中...',
        forbidClick: true,
        duration: 0,
      });
      state.posterData = { ...data }
      await url2Base64(data.headImg)
      state.shopQrCode = getUrl(data)
      state.off.overlay = true
      state.off.share = true

      nextTick(() => {
        let posterDOM = document.getElementById('posterHtml')
        html2canvas(posterDOM, {
          width: posterDOM.offsetWidth,
          height: posterDOM.offsetHeight,
          //按比例增加分辨率
          scale: window.devicePixelRatio, // 设备像素比
          useCORS: true,//（图片跨域相关）
          allowTaint: true,//允许跨域（图片跨域相关）
          logging: false,
          letterRendering: true,
        }).then(function (canvas) {
          state.posterImgURL = canvas.toDataURL('image/png')
        })
      })

      closeToast()
    }

    async function url2Base64(url) {
      const obj = {
        url
      }
      await api.imgtobase64(obj).then(res => {
        if (res.code == '200') {
          if (!res.data || !res.data.info) {
            showToast('商品图片生成失败')
          }
          state.posterData.headImg = res.data.info
        } else {
          showToast(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    // 下载海报
    const downloadPoster = (base64, fileName) => {
      showLoadingToast({
        message: '保存中...',
        forbidClick: true,
        duration: 0,
      });
      if (state.isApp) {
        JsBridge.callHandler('saveFileByBase64', { base64, fileName: fileName + '.png' }, (res) => {
          console.log(res)
          successDeal('保存成功，请前往相册查看！')
        })
      } else {
        saveImg(base64ToUrl(base64), fileName + '.png')
        closeToast()
      }
    }

    function base64ToUrl(imgdata) {
      let base = imgdata
      if (imgdata.indexOf('data:image/png;base64' > -1)) {
        base = imgdata.split(",")[1]
      }
      const byteCharacters = atob(base)
      const byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      const byteArray = new Uint8Array(byteNumbers)
      const blob = new Blob([byteArray], { type: "image/jpeg" })
      let binaryData = []
      binaryData.push(blob)
      let url = URL.createObjectURL(new Blob(binaryData))
      return url
    }

    function saveImg(url, fileName) {
      const a = document.createElement('a')
      a.setAttribute('download', fileName)
      a.href = url
      a.click()
    }

    const handleShare = (option) => {
      if (option.name == '保存图片') {
        var reg1 = new RegExp("/", "g");
        var fileName = state.posterData.goodsName.replace(reg1, "").replace(/[\\]/g, '');
        downloadPoster(state.posterImgURL, fileName)
      }
      if (option.name == '微信') {
        let url = getUrl(state.posterData)
        const data = {
          type: "wechat_session",
          url: url,
          key: "wx15c4f6e4eaa14443",
          title: '秒返宝',
          description: state.posterData.goodsName
        }
        JsBridge.callHandler('share', data, (res) => {
          console.log('share 响应值 ： ', res);
        })
      }
      state.off.share = false
      state.off.overlay = false
    }

    function handleCopy(value) {
      const input = document.createElement('input');
      document.body.appendChild(input)

      let url = getUrl(value)
      input.setAttribute('value', url);
      input.select();
      if (document.execCommand('copy')) {
        document.execCommand('copy');
        successDeal('复制成功！')
      }
      document.body.removeChild(input);
    }

    const getUrl = (value) => {
      let url = ``
      let shopName = encodeURI(state.shopForm.shopName)
      if (WEB_SOURCE.mode == "master") {
        url = `https://miaofanbao.yilianyun.top/manager/#/h5goods?m=${state.shopForm.shopId}&u=${state.userInfo.userId}&n=${shopName}&g=${value.goodsId}`
      } else {
        url = `http://192.168.10.31:5001/miaofan_web/#/h5goods?m=${state.shopForm.shopId}&u=${state.userInfo.userId}&n=${shopName}&g=${value.goodsId}`
      }
      return url
    }

    const openIncome = (incomeConfList) => {
      state.off.income = true
      state.incomeConfList = incomeConfList
    }

    const toMsg = () => {
      router.push({
        path: `/msg`
      })
    }

    const pageJump = (path, params) => {
      router.push({
        path,
        query: {
          goodsId: params.goodsId,
          goodsName: params.goodsName
        }
      })
    }

    const toShopShare = () => {
      router.push({
        path: '/more/shop/cardQr'
      })
    }

    const toLinkUrl = (data) => {
      if (data.linkUrl) {
        if (state.isApp) {
          JsBridge.callHandler('openUrl', { url: data.linkUrl }, (res) => {
            console.log('openUrl', res)
          })
        } else {
          window.open(data.linkUrl, '_blank')
        }
      }
    }

    onBeforeUnmount(() => {
      clearInterval(state.timer)
    })

    return {
      ...toRefs(state),
      toThousands,
      onLoad,
      onRefresh,
      createPoster,
      downloadPoster,
      handleCopy,
      handleShare,
      handleSearch,
      openIncome,
      pageJump,
      toMsg,
      toShopShare,
      toLinkUrl,
    }
  }
}
</script>
<style lang='scss' scoped>
.f-index {
  padding: 0 !important;
  display: flex;
  flex-direction: column;
  .f-header {
    padding-top: 27px;
    display: flex;
    align-items: center;
    background: #0f9bfd;
    .f-logo {
      width: 28px;
      height: 28px;
      border-radius: 50%;
      background: #fff;
      margin-left: 12px;

      line-height: 28px;
      font-size: 9px;
      color: #0f9bfd;
      img {
        border-radius: 50%;
      }
    }
    .f-msg {
      width: 23px;
      height: 18px;
      margin-right: 15px;
      margin-left: 5px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .f-banner {
    width: 100%;
    height: 160px;
    position: relative;
  }
  .f-tab {
    display: flex;
    align-items: center;
    margin: 10px 14px 15px 18px;
    li {
      height: 24px;
      border-radius: 12px;
      padding: 0 8px;
      color: #666666;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
    }
    li:not(:first-child) {
      margin-left: 20px;
    }
    .f-activeTab {
      background: #ff635d;
      color: #fff;
    }
  }
  .f-cell-ground {
    margin: 0 14px;
    padding-top: 11px;
    .f-cell {
      position: relative;
      width: 347px;
      background: #ffffff;
      border-radius: 5px;
      margin-bottom: 23px;
      .f-goods-img {
        width: 88px;
        height: 87px;
        border-radius: 5px;
        position: absolute;
        top: -10px;
      }
      .f-tips {
        margin: 0 5px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 5px 0 10px;
        width: 337px;
        height: 21px;
        background: #e4f2ff;
        font-size: 11px;
        font-weight: 300;
        color: #424242;
      }
      .f-type {
        width: 45px;
        padding-top: 2px;
        height: 18px;
        border-radius: 10px;
        border: 1px solid #488bfe;
        font-weight: 300;
        font-size: 10px;
        color: #488bfe;
        text-align: center;
        margin-bottom: 10px;
        margin-left: 9px;
      }
      .f-btn {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 13px 0;
        p {
          width: 50%;
          text-align: center;
          font-size: 14px;
          color: #000000;
        }
        p:not(:first-child) {
          border-left: 1px solid #666666;
        }
      }
    }
  }
  .f-overlay {
    background-image: url("@/assets/imgs/bg_poster.png");
    background-size: 315px 444px;
    height: 444px;
    width: 315px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -60%);
    .f-overlay-card {
      width: 231px;
      height: 252px;
      background: #ffffff;
      border-radius: 10px;
      margin-left: 42px;
      margin-top: 45px;
      padding: 14px 12px 19px 12px;
      .f-content {
        margin-top: 5px;
        width: 208px;
        background: #e4f2ff;
        border-radius: 10px;
        padding: 10px 14px;
        font-size: 11px;
        font-weight: 300;
        color: #424242;
        line-height: 20px;
      }
    }
    .f-shop-info {
      width: 315px;
      height: 90px;
      background: #1e66d6;
      margin-top: 57px;
      border-radius: 0 0 10px 10px;
      color: #ffffff;
      line-height: 90px;
      padding: 0 20px 0 14px;
      position: relative;
      .f-qr-code {
        position: absolute;
        right: 20px;
        top: -26px;
        line-height: 0;
        text-align: center;
      }
    }
    .f-btn-box {
      position: absolute;
      bottom: -55px;
      width: 315px;
      padding: 0 13px;
      display: flex;
      justify-content: space-between;
      p {
        width: 102px;
        height: 37px;
        background: #1e66d6;
        border-radius: 19px;

        font-size: 16px;
        font-weight: 400;
        color: #ffffff;
        line-height: 37px;
        text-align: center;
      }
    }
  }
  .f-wrapper {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -60%);

    width: 305px;
    background: #ffffff;
    border-radius: 7px;
    text-align: center;
    padding: 20px 0;
    ul {
      margin-top: 20px;
      li {
        display: flex;
        margin: 5px 0;
        font-size: 14px;
        color: #ff6868;
        p:first-child {
          width: 190px;
          text-align: right;
          color: #707070;
        }
      }
    }
  }
}
</style>